﻿using IGF.Utils;
using LikeProxy.Controls.RequestBodyType;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace LikeProxy.Controls
{
    public partial class RequestControl : UserControl
    {
        FormUrlencodedControl formUrlencodedControl = new FormUrlencodedControl();
        BinaryControl binaryControl = new BinaryControl();
        FormDataControl formDataControl = new FormDataControl();
        RawControl rawControl = new RawControl();
        public RequestControl()
        {
            InitializeComponent();
        }

        private void RequestControl_Load(object sender, EventArgs e)
        {
            cb_req_method.SelectedIndex = 0;
            rBtn_set_headers_list.Checked = true;
            dataGV_req_headers.Height = 600;
            rBtn_body_type2.Checked = true;
        }

        // <summary>
        /// 网络请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRequestClick(object sender, EventArgs e)
        {

            try
            {
                // 验证请求URL
                string url = textBox_req_url.Text;
                if (!url.StartsWith("http"))
                {
                    url = "http://" + url;
                }
                HttpItem hi = new HttpItem
                {
                    URL = url,
                    WebProxy = new WebProxy("127.0.0.1", 8899),
                    ResultType = ResultType.String,
                    PostDataType = PostDataType.String,
                    PostEncoding = Encoding.UTF8,
                    Timeout = 50000,
                    Allowautoredirect = true,
                };


                // 设置请求Headers
                var headers = GetRequestHeaders();
                hi.AddHeaders(headers);
                hi.Method = cb_req_method.SelectedItem.ToString();
                // postData设置
                if (rBtn_body_type1.Checked)//form-data
                {

                }
                else if (rBtn_body_type2.Checked)//x-www-form-urlencoded
                {
                    var body = formUrlencodedControl.GetRequestBody();
                    if (!headers.ContainsKey("Content-Type") && !headers.ContainsKey("content-type"))
                    {
                        hi.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                    }
                    List<string> list = new List<string>();
                    foreach (var item in body)
                    {
                        list.Add(item.Key + "=" + item.Value);
                    }
                    hi.Postdata = string.Join("&", list.ToArray());
                }
                else if (rBtn_body_type3.Checked)//raw
                {
                    hi.Postdata = rawControl.GetBodyText();
                }
                else if (rBtn_body_type4.Checked)//binary
                {

                }
                // 响应体设置 
                HttpResult hr = new HttpHelper().GetHtml(hi);
                textBox_res_content.Text = hr.Html.Trim();
                dataGV_res_headers.Rows.Clear();
                foreach (var key in hr.Header.AllKeys)
                {
                    dataGV_res_headers.AddRow(new object[]
                    {
                        key,
                        hr.Header[key],
                    });
                }
            }
            catch (Exception ex)
            {

            }
        }
        private Dictionary<string, string> GetRequestHeaders()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            if (rBtn_set_headers_text.Checked)
            {
                foreach (var item in textBox_req_headers.Text.Split(Environment.NewLine.ToCharArray()))
                {
                    var keyValue = item.Split(':');
                    var reg = Regex.Match(item, "(.*?):(.*)");
                    if (reg.Groups.Count == 3)
                    {
                        headers.Add(reg.Groups[1].Value.Trim(), reg.Groups[2].Value.Trim());
                    }
                    //if (keyValue.Length == 2)
                    //{
                    //    headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
                    //}
                }
            }
            else
            {
                foreach (DataGridViewRow item in dataGV_req_headers.Rows)
                {
                    if (item.Cells[1].Value == null)
                    {
                        continue;
                    }
                    bool has = (bool)item.Cells[0].Value;
                    string key = (string)item.Cells[1].Value;
                    string value = item.Cells[2].Value == null ? "" : (string)item.Cells[2].Value;
                    if (has == true && key != "")
                    {
                        headers.Add(key, value);
                    }
                }
            }
            return headers;
        }



        private void RadioButtonCheckedChanged(object sender, EventArgs e)
        {
            RadioButton btn = sender as RadioButton;
            if (btn.Checked == true)
            {
                textBox_req_headers.Visible = rBtn_set_headers_text.Checked;
                dataGV_req_headers.Visible = rBtn_set_headers_list.Checked;

                if (btn.Name == "rBtn_set_headers_list")
                {
                    dataGV_req_headers.Location = new Point(9, 32);
                    dataGV_req_headers.Rows.Clear();
                    foreach (var item in textBox_req_headers.Text.Split(Environment.NewLine.ToCharArray()))
                    {
                        var reg = Regex.Match(item, "(.*?):(.*)");
                        if (reg.Groups.Count == 3)
                        {
                            dataGV_req_headers.AddRow(new object[]
                            {
                                true,
                                reg.Groups[1].Value.Trim(),
                                reg.Groups[2].Value.Trim(),
                            });
                        }
                    }

                }
                else if (btn.Name == "rBtn_set_headers_text")
                {
                    List<string> datas = new List<string>();
                    foreach (DataGridViewRow item in dataGV_req_headers.Rows)
                    {
                        if (item.Cells[1].Value == null || item.Cells[2].Value == null)
                        {
                            continue;
                        }
                        bool has = (bool)item.Cells[0].Value;
                        string key = (string)item.Cells[1].Value;
                        string value = (string)item.Cells[2].Value;
                        if (has == true && key != "")
                        {
                            datas.Add($"{key}:{value}");
                        }
                    }
                    textBox_req_headers.Text = string.Join(Environment.NewLine, datas.ToArray());
                    textBox_req_headers.Location = new Point(9, 32);
                }
                else if (btn.Name == "rBtn_body_type1")
                {
                    panel_body_type_control.Controls.Clear();
                    panel_body_type_control.Controls.Add(formDataControl);
                }
                else if (btn.Name == "rBtn_body_type2")
                {
                    panel_body_type_control.Controls.Clear();
                    panel_body_type_control.Controls.Add(formUrlencodedControl);
                }
                else if (btn.Name == "rBtn_body_type3")
                {
                    panel_body_type_control.Controls.Clear();
                    panel_body_type_control.Controls.Add(rawControl);
                }
                else if (btn.Name == "rBtn_body_type4")
                {
                    panel_body_type_control.Controls.Clear();
                    panel_body_type_control.Controls.Add(binaryControl);
                }
            }
        }

        private void btn_to_jsonEditor_Click(object sender, EventArgs e)
        {
            MainForm mainForm = this.ParentForm as MainForm;
            mainForm.TransferToJSONEditor(textBox_res_content.Text);
        }
    }
}
